import 'dart:async';
import 'dart:isolate';

import 'package:flutter/material.dart';

class StreamBuildDemo extends StatefulWidget {
  const StreamBuildDemo({Key? key}) : super(key: key);

  @override
  State<StreamBuildDemo> createState() => _StreamBuildDemoState();
}

class _StreamBuildDemoState extends State<StreamBuildDemo> {
  int a = 0;
  // 1、声明一个StreamController类型的控制器，命名为streamController；
  final StreamController<int> streamController = StreamController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 2、将需要局部刷新数据的组件嵌套在StreamBuilder组件内，并接收信息；
            StreamBuilder<int>(
              stream: streamController.stream,
              initialData: a,
              builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                return Text('a : $a');
              },
            ),
            ElevatedButton(
              onPressed: () {
                a++;
                setState(() {});
              },
              child: const Text('setState'),
            ),
            ElevatedButton(
              onPressed: () {
                a++;
                // 3、往`StreamBuilder`里添加数据，并通知`StreamBuilder`重新构建；
                streamController.add(a);
              },
              child: const Text('streamBuilder'),
            ),
          ],
        ),
      ),
    );
  }

  test() {
    StreamSubscription<String> subscription;
    //创建StreamController
    var streamController = StreamController<String>();
    // 获取StreamSink用于发射事件
    StreamSink<String> streamSink = streamController.sink;
    // 获取Stream用于监听
    Stream<String> streamData = streamController.stream;
    //监听事件
    subscription = streamData.listen((value) {
      // do something
    });
    //发射一个事件.
    streamSink.add("111");
    streamController.close();
  }

  //----------
  test22() {
    Completer<int> completer = Completer<int>();

// 假设在两秒钟后异步返回一个值
    Future.delayed(const Duration(seconds: 2), () {
      completer.complete(42);
    });

// 使用then()方法等待异步操作的结果
    completer.future.then((value) {
      print('异步操作的结果为：$value');
    });
  }
  //----------

  //----------
  Future<void> calculate() async {
    ReceivePort receivePort = ReceivePort();

    await Isolate.spawn(calculateFibonacci, 20, onExit: receivePort.sendPort);

    int result = await receivePort.first;
    print('计算结果为：$result');
  }

  void calculateFibonacci(int n) {
    // 计算斐波那契数列的第n项，并将结果发送到主Isolate
    // int result = fibonacci(n);
    // SendPort sendPort = IsolateNameServer.lookupPortByName('main_send_port');
    // sendPort.send(result);
  }

  //----------

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    // 4、关流，避免内存泄漏
    streamController.close();
  }
}
